package com.mask.sca.core.exception;

import com.mask.sca.core.response.ApiResponse;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 处理业务异常
    @ExceptionHandler(BusinessException.class)
    public ApiResponse<?> handleBusinessException(BusinessException e) {
        log.warn("业务异常: code={}, message={}", e.getCode(), e.getMessage());
        return ApiResponse.fail(e.getCode(), e.getMessage());
    }

    // 处理参数校验异常（MethodArgumentNotValidException）
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        String errorMessage = fieldErrors.isEmpty() ? 
            "参数校验失败" : fieldErrors.get(0).getDefaultMessage();
        log.warn("参数校验异常: {}", errorMessage);
        return ApiResponse.fail(ErrorCode.PARAM_ERROR.getCode(), errorMessage);
    }

    // 处理参数绑定异常（BindException）
    @ExceptionHandler(BindException.class)
    public ApiResponse<?> handleBindException(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        String errorMessage = fieldErrors.isEmpty() ? 
            "参数绑定失败" : fieldErrors.get(0).getDefaultMessage();
        log.warn("参数绑定异常: {}", errorMessage);
        return ApiResponse.fail(ErrorCode.PARAM_ERROR.getCode(), errorMessage);
    }

    // 处理HTTP消息解析异常
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ApiResponse<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.warn("HTTP消息解析异常: {}", e.getMessage());
        return ApiResponse.fail(ErrorCode.PARAM_ERROR.getCode(), "请求参数格式错误");
    }

    // 处理Feign远程调用异常
    @ExceptionHandler(FeignException.class)
    public ApiResponse<?> handleFeignException(FeignException e) {
        log.error("Feign远程调用异常: status={}, message={}", e.status(), e.getMessage(), e);
        return ApiResponse.fail(ErrorCode.FEIGN_ERROR.getCode(), "远程服务调用失败");
    }

    // 处理未定义的其他异常
    @ExceptionHandler(Exception.class)
    public ApiResponse<?> handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return ApiResponse.fail(ErrorCode.SYSTEM_ERROR.getCode(), "系统繁忙，请稍后重试");
    }
}